package com.chang.service;

import com.chang.pojo.Order;
import com.chang.tools.Tools;
import com.chang.pojo.Goods;
//import lombok.Data;

import java.io.*;
import java.util.*;

public class GoodsService {
    private String filename;
    public HashMap<String, Goods> goodsHashMap = new HashMap<>();
    public HashMap<String, Order> orderHashMap = new HashMap<>();
    File file;
    File ofile;
    Scanner scanner;
    Tools tools;

    public GoodsService() throws IOException {
        scanner = new Scanner(System.in);
        tools =new Tools();
        filename= tools.File_Path;
        file = new File(filename+"\\src\\com\\chang\\db\\goodsInfo.txt");
        ofile = new File(filename+"\\src\\com\\chang\\db\\orderinfo.txt");
        readGoods();
        readOrder();
    }
    public void readOrder() throws IOException {
        FileReader read = new FileReader(ofile);
        BufferedReader sr =new BufferedReader(read);
        String str;
        while ((str=sr.readLine())!=null){
            String[] order_arr=str.split(",");
            Order order=new Order();
            order.setCode(order_arr[0]);
            order.setUserid(order_arr[1]);
            order.setGoodsid(order_arr[2]);
            order.setNum(Integer.parseInt(order_arr[3]));
            orderHashMap.put(order.getUserid(),order);
        }
    }
    public void writeOrder() throws IOException {
        String all_txt = "";
        Set<String> keyset = orderHashMap.keySet();
        Iterator<String> iterator = keyset.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Order value = orderHashMap.get(key);
            all_txt += value.txtorder();
        }
        FileWriter writer = new FileWriter(ofile);
        writer.write(all_txt);
        writer.flush();
    }
    public void readGoods() throws IOException {
        FileReader reader = new FileReader(file);// 低级流
        BufferedReader br = new BufferedReader(reader);
        String str;
        while ((str = br.readLine()) != null) {
            String[] good_arr = str.split(",");
            Goods goods = new Goods();
            goods.setGoodsName(good_arr[0]);
            goods.setGoodsId(good_arr[1]);
            goods.setInventory(Integer.parseInt(good_arr[2]));
            goods.setPrice(Double.parseDouble(good_arr[3]));
            goods.setTime(Integer.parseInt(good_arr[4]));
            goodsHashMap.put(goods.getGoodsId(), goods);
        }
    }public Goods searchGoods(String name){
        Set<String> keyset=goodsHashMap.keySet();
        Iterator<String> iterator= keyset.iterator();
        while (iterator.hasNext()){
            String key=iterator.next();
            String value=goodsHashMap.get(key).getGoodsName();
            if(value.equalsIgnoreCase(name)) return goodsHashMap.get(key);
        }
        return null;
    }

    public void updateGoods(Goods goods) throws IOException, InterruptedException {
        if(searchGoods(goods.getGoodsName())!=null) {
            System.out.println("识别到已拥有的商品,正在为您更改内容...");
            System.out.println("更改中...");
            Goods goods1 = goodsHashMap.get(searchGoods(goods.getGoodsName()).getGoodsId());
            goods1.setInventory(goods.getInventory());
            goods1.setPrice(goods.getPrice());
            Thread.sleep(1000);
            System.out.println("更改成功!");
        } else {
            String sid;
            System.out.println("正在为您添加商品，请稍后...");
            boolean ti = false;
            do {
                sid = "" + (int) (1000 + (Math.random() * 9000));
                if(goodsHashMap.get(sid)!=null){
                    ti=true;
                }else {
                    ti=false;
                }
            }while (ti);
            Thread.sleep(1000);
            goods.setGoodsId(sid);
            goodsHashMap.put(sid,goods);
            System.out.println("添加成功!");
        }
        System.out.println("----------------");
        writeGoods();
    }

    public void deleteGoods() throws InterruptedException, IOException {
        boolean p = false;
        String iname;
        do {
            findAllGoods();
            System.out.print("请输入您要要删除的商品(id)：");
            iname = scanner.next();
            if (goodsHashMap.get(iname) == null) {
                System.out.println("该商品信息不存在,请您重新输入。");
                p = true;
            } else {
                p = false;
            }
        } while (p);
        System.out.println("正在为您删除商品，请稍后...");
        Thread.sleep(1000);
        goodsHashMap.remove(iname);
        System.out.println("删除成功！");
        System.out.println("----------------");
        writeGoods();
    }

    public void findGoods() {
        boolean op = true;
        String id;
        do {
            System.out.print("请输入您想查询的商品(id):");
            id = scanner.next();
            if (goodsHashMap.get(id) == null) {
                System.out.println("该商品信息不存在,请您重新输入。");
                op = true;
            } else {
                op = false;
            }
        } while (op);
        Goods goods = goodsHashMap.get(id);
        System.out.println("该商品信息如下:");
        System.out.println(goods.getGoodsName()+",共售出:"+goods.getTime()+"件,共售"+(goods.getTime()*goods.getPrice())+"元");
    }

    public void findAllGoods() {
        System.out.println("您可以选择的商品有:");
        Set<String> keyset = goodsHashMap.keySet();
        Iterator<String> iterator = keyset.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Goods value = goodsHashMap.get(key);
            System.out.println("id:"+value.getGoodsId()+",商品名:"+value.getGoodsName() + ",售价:" + value.getPrice() + "元/件,商品库存:" + value.getInventory());
        }
    }

    public void purchase(String userid) throws IOException, InterruptedException {
        String id;
        boolean po = false;
        do{
            tools.clearScreen();
            findAllGoods();
            System.out.print("请输入商品id:");
            id=scanner.next();
            if(goodsHashMap.get(id)==null){
                System.out.println("未查询商品,请重试");
                po=true;
            }else {
                po=false;
            }
        }while (po);
        boolean op = false;
        String num;
        Goods goods = goodsHashMap.get(id);
        do {
            System.out.print("请输入您想购买的商品数量：");
            num = scanner.next();
            if(!num.matches("\\d+")){
                System.out.println("您输入的内容有误，请重试");
                op=true;
            }
            else if (Integer.parseInt(num) > goods.getInventory()) {
                System.out.println("抱歉，我们的库存不足，请您重新输入。");
                op = true;
            } else {
                op = false;
            }
        } while (op);
        goods.setInventory(goods.getInventory() - Integer.parseInt(num));
        goods.setTime(goods.getTime() + Integer.parseInt(num));
        writeGoods();
        System.out.println("正在支付中，请稍后...");
        Order order=new Order();
        boolean bhg=false;
        String code;
        do{
            code="Tn"+(int) (1000 + (Math.random() * 90000));
            if(orderHashMap.get(code)!=null){
                bhg=true;
            }else {
                bhg=false;
            }
        }while (bhg);
        order.setCode(code);
        order.setUserid(userid);
        order.setGoodsid(goods.getGoodsId());
        order.setNum(Integer.parseInt(num));
        orderHashMap.put(order.getCode(),order);
        writeOrder();
        Thread.sleep(1000);
        System.out.println("支付成功！");
    }
    public void searchOwnOeder(String userid) throws IOException, InterruptedException {
        HashMap<String,Order> ownorder=new HashMap<>();
        Set<String> keyset=orderHashMap.keySet();
        Iterator<String> iterator= keyset.iterator();
        String allorder="";
        while (iterator.hasNext()){
            String key=iterator.next();
            Order value=orderHashMap.get(key);
            Goods goods=goodsHashMap.get(value.getGoodsid());
            if(userid.equals(value.getUserid())){
               ownorder.put(key,value);
               allorder+="账单编号:"+key+",商品名:"+goods.getGoodsName()+",数量:"+value.getNum()+",实付款:"+(value.getNum())*goods.getPrice()+"元\n";
            }
        }
        if(allorder.equals("")){
            System.out.println("您没买过东西!");
            return;
        }
        System.out.println("您的订单有:");
        System.out.println(allorder);
        boolean tg=false;
        String bf;
        do{
            System.out.print("是否退款?(Y|N)");
            bf=scanner.next();
            if(bf.equalsIgnoreCase("n")){
                return;
            }else if(bf.equalsIgnoreCase("y")){
                tools.clearScreen();
                tg=false;
            }else {
                System.out.println("您输入的内容有误,请重试!");
                tg=true;
            }
        }while (tg);
        do{
            tools.clearScreen();
            System.out.print("请输入您要退款商品的订单编号:");
            bf=scanner.next();
            if(ownorder.get(bf)==null){
                System.out.println("您输入的内容有误，请重试!");
                tg=true;
            }else{
                tg=false;
                System.out.println("退款中...");
                Order order=orderHashMap.get(bf);
                orderHashMap.remove(bf);
                writeOrder();
                if(goodsHashMap.get(order.getGoodsid())!=null){
                    Goods goods=goodsHashMap.get(order.getGoodsid());
                    goods.setInventory(goods.getInventory()+order.getNum());
                    goods.setTime(goods.getTime()-order.getNum());
                    writeGoods();
                }
                ownorder.remove(bf);
                Thread.sleep(1000 );
                System.out.println("退款成功!");
            }
        }while (tg);
    }

    public void writeGoods() throws IOException {
        String all_txt = "";
        Set<String> keyset = goodsHashMap.keySet();
        Iterator<String> iterator = keyset.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Goods value = goodsHashMap.get(key);
            all_txt += value.getGoodsName() + "," + value.getGoodsId() + "," + value.getInventory() + "," + value.getPrice() + "," + value.getTime() + "\n";
        }
        FileWriter writer = new FileWriter(file);
        writer.write(all_txt);
        writer.flush();
    }

    public void findAllTimes() {//销量统计
        Set<String> keyset = goodsHashMap.keySet();
        Iterator<String> iterator = keyset.iterator();
        int sum=0;
        while (iterator.hasNext()) {
            String key = iterator.next();
            int value = goodsHashMap.get(key).getTime();
            System.out.print("商品:" + goodsHashMap.get(key).getGoodsName());
            System.out.println();
            System.out.print("已售出:" + value);
            System.out.println();
            sum+=value;
        }
        System.out.println("共售出"+sum+"件商品");
    }

    public void findAllInventory() {//库存统计
        Set<String> keyset = goodsHashMap.keySet();
        Iterator<String> iterator = keyset.iterator();
        int sum=0;
        while (iterator.hasNext()) {
            String key = iterator.next();
            int value = goodsHashMap.get(key).getInventory();
            System.out.print("商品:" + goodsHashMap.get(key).getGoodsName());
            System.out.println();
            System.out.print("库存:" + value);
            System.out.println();
            sum+=value;
        }
        System.out.println("商品总库存"+sum+"件");
    }
}
